package com.hjjt.baselib.util

import android.content.Context
import android.speech.tts.TextToSpeech
import android.util.Log
import java.util.*

/**
 *
 * @ProjectName:    IntelligentTerminal
 * @Package:        com.hjiot.viewlib.util
 * @ClassName:      TTSManger
 * @Description:
 * @Author:         孙浩
 * @CreateDate:     2022/8/10 16:17
 */
class TTSManger private constructor() {

    var speaker: TextToSpeech? = null
    var initSpeakerComplete = false
    var langSupport = false

    companion object {
        val instance by lazy {
            TTSManger()
        }
    }

    fun initContext(context: Context){
        createSpeaker(context)
    }

    private fun createSpeaker(context: Context) {
        speaker = TextToSpeech(context) {
            if (TextToSpeech.SUCCESS == it) {
                initSpeakerComplete = true
                speaker?.setLanguage(
                    Locale.CHINESE
                ).let { result ->
                    if (!(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)) {
                        langSupport = true
                    }
                }
            }
        }
    }

    fun speakText(msg: String) {
        Log.e("TTSManger", "speakText: $msg", )
        if (!initSpeakerComplete || !langSupport) return
        speaker?.run {
            if (isSpeaking) return@run
            this.speak(msg, TextToSpeech.QUEUE_FLUSH, null)
        }
    }
}
